<template>
    <view>
        <u-toast ref="uToast" /><u-no-network></u-no-network>
        <u-navbar title="提交售后" safeAreaInsetTop fixed placeholder>
            <view class="coreshop-navbar-left-slot" slot="left">
                <u-icon name="arrow-left" size="19" @click="goNavigateBack"></u-icon>
                <u-line direction="column" :hairline="false" length="16" margin="0 8px"></u-line>
                <u-icon name="home" size="22" @click="goHome"></u-icon>
            </view>
            <view slot="right">
            </view>
        </u-navbar>
        <view class="content">
            <view class="coreshop-margin-5">
                <u-alert type="warning" effect="dark" :description="alertDescription"></u-alert>
            </view>
            <form @submit="submit">
                <view class="coreshop-tabbar-height">
                    <view class='coreshop-cell-group coreshop-margin-top-10 coreshop-margin-bottom-10'>
                        <view class='coreshop-cell-item'>
                            <view class='coreshop-cell-item-hd'>
                                <view class='coreshop-cell-hd-title'>售后模式</view>
                            </view>
                            <view class='coreshop-cell-item-ft'>
                                <view class="uni-form-item uni-column invoice-type">
                                    <!-- #ifndef MP-ALIPAY -->
                                    <radio-group class="uni-list" @change="radioChange">
                                        <label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in typeList"
                                            :key="index">
                                            <view class="invoice-type-icon">
                                                <radio class="a-radio radioNo" v-if="item.disabled" :id="item.name" :value="item.value" :checked="item.checked" :disabled="item.disabled"></radio>
                                                <radio class="a-radio " v-else :id="item.name" :value="item.value" :checked="item.checked" :disabled="item.disabled"></radio>
                                            </view>
                                            <view class="invoice-type-c">
                                                <label :for="item.name">
                                                    <text>{{ item.name }}</text>
                                                </label>
                                            </view>
                                        </label>
                                    </radio-group>
                                    <!-- #endif -->
                                    <!-- #ifdef MP-ALIPAY -->
                                    <radio-group class="uni-list" @change="radioChange">
                                        <label class="uni-list-cell uni-list-cell-pd"
                                            v-for="(item, index) in typeListByAli" :key="index">
                                            <view class="invoice-type-icon">
                                                <radio class="a-radio" :id="item.name" :value="item.value" :checked="item.checked" :disabled="item.disabled"></radio>
                                            </view>
                                            <view class="invoice-type-c">
                                                <label class="label-2-text" :for="item.name">
                                                    <text>{{ item.name }}</text>
                                                </label>
                                            </view>
                                        </label>
                                    </radio-group>
                                    <!-- #endif -->
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="img-list">
                        <view class="list-box" v-for="(item, key) in items" :key="key">
                            <checkbox-group class="cart-checkbox" @change="checkboxChange" :data-idx="key"
                                :data-itemid="item.id">
                                <view class="cart-checkbox-item">
                                    <label class="uni-list-cell uni-list-cell-pd">
                                        <view class="cart-checkbox-c">
                                            <checkbox :value='item.id' :checked="item.checked" color="#FF7159"
                                                v-if="item.disabled" :disabled="item.disabled" class="checkboxNo" />
                                            <checkbox :value='item.id' :checked="item.checked" color="#FF7159" v-else />
                                        </view>
                                        <view class="img-list-item coreshop-flex coreshop-justify-between">
                                            <u-avatar :src="item.imageUrl" mode="square" size="75"
                                                class="img-list-item-l"></u-avatar>
                                            <view class="img-list-item-r">
                                                <view class="list-goods-name">
                                                    {{ item.name }}
                                                </view>
                                                <view
                                                    class="goods-item-c coreshop-margin-top-5 coreshop-margin-bottom-5"
                                                    v-if="item.addon">
                                                    <view class="goods-buy">
                                                        <!-- 商品规格 -->
                                                        <view class="goods-salesvolume coreshop-margin-right-10 ">
                                                            {{ item.addon }}
                                                        </view>
                                                    </view>
                                                </view>
                                                <view class="goods-item-c">
                                                    <view class="goods-buy">
                                                        <!-- 商品规格 -->
                                                        <view class="goods-salesvolume coreshop-margin-right-10">
                                                            购买数：{{ item.nums }}
                                                        </view>
                                                        <view class="goods-salesvolume coreshop-margin-right-10">
                                                            发货数量：{{ item.sendNums }}
                                                        </view>
                                                        <view class="goods-salesvolume coreshop-margin-right-10"
                                                            v-show="item.reshipNums != 0">
                                                            已退数量：{{ item.reshipNums }}
                                                        </view>
                                                        <!-- <view
                                                            class="goods-salesvolume  coreshop-margin-top-15 coreshop-margin-bottom-10"
                                                            v-if="!item.disabled">
                                                            <label>您要退货数量：</label> 
                                                            <input type="number" v-model="item.returnNums" @focus="onFocus(item,key)" @blur="updateNum(item,key)" class="inputStyle" ref="input" @click.stop />
                                                        </view> -->
                                                    </view>
                                                </view>
                                            </view>
                                        </view>
                                    </label>
                                </view>
                            </checkbox-group>
                            <view class="goods-flex" v-if="item.sendNums > 0">
                                <label>您要退货数量：</label>
                                <u-number-box :button-size="25" :integer="true" v-model="item.returnNums" :disabledInput="true" :min="item.min" :max="item.max" @change="hanlderChangeReturnNums($event,key)"></u-number-box>
                            </view>
                        </view>
                    </view>

                    <view class='coreshop-cell-group coreshop-margin-top-10 coreshop-margin-bottom-10'>
                        <view class='coreshop-cell-item refund-price'>
                            <view class='coreshop-cell-item-hd'>
                                <view class='coreshop-cell-hd-title'>退款金额</view>
                            </view>
                            <view class='coreshop-cell-item-ft'>
                                <input type="digit" class='coreshop-cell-bd-input coreshop-text-red' v-model="refund" @focus="refundFocus" ref="refund"></input>
                            </view>
                        </view>
                        <view class=" coreshop-font-12 refund-tip">
                            可修改，最多￥{{ maxRefund }}，含发货邮费￥{{ costFreight }}
                        </view>
                    </view>
                    <view class='coreshop-cell-group coreshop-margin-top-10 coreshop-margin-bottom-10'>
                        <view class='coreshop-cell-item right-img'>
                            <view class='coreshop-cell-item-hd'>
                                <view class='coreshop-cell-hd-title'>上传凭证</view>
                            </view>
                            <view class='coreshop-cell-item-ft coreshop-margin-right-10'>{{ images.length }}/{{ imageMax
                                }}
                            </view>
                        </view>
                        <view class="">
                            <view class="evaluate-c-b">
                                <view class="goods-img-item" v-for="(item, key) in images" :key="key">
                                    <image class="del" src="/static/images/common/del.png" mode=""
                                        @click="delImage(item)"></image>
                                    <image class="" :src="item" mode="" @click="clickImg(item)"></image>
                                </view>
                                <view class="upload-img" v-show="isImage" @click="upImage">
                                    <image class="icon" src="/static/images/common/camera.png" mode=""></image>
                                    <view class="">上传照片</view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class='coreshop-cell-group coreshop-margin-top-10 coreshop-margin-bottom-10'>
                        <view class='coreshop-cell-item right-img'>
                            <view class='coreshop-cell-item-hd'>
                                <view class='coreshop-cell-hd-title'>问题描述</view>
                            </view>
                        </view>
                        <view class="cell-textarea">
                            <u--textarea v-model="reason" placeholder="请您在此描述问题(最多200字)" :count="true"></u--textarea>
                        </view>
                    </view>
                    <view class="coreshop-bottomBox">
                        <button class="coreshop-btn coreshop-btn-b coreshop-btn-square" formType="submit" :disabled='submitStatus' :loading='submitStatus'>提交</button>
                    </view>
                </view>
            </form>
        </view>
    </view>

</template>

<script>
export default {
    data() {
        return {
            typeList: [
                { value: '1', name: '仅退款', checked: true, disabled: false },
                { value: '2', name: '退货退款', checked: false, disabled: false },
            ],
            typeListByAli: [
                { value: '1', name: '仅退款', checked: true, disabled: false },
                { value: '2', name: '退货退款', checked: false, disabled: false },
            ],
            orderId: '',
            items: [],   //退货明细
            itemIds: [],  //选择的退货
            aftersaleType: 1,     //售后类型1退款，2退款退货
            refund: 0,   //退款金额，等于已支付的金额减去已退款的金额
            maxRefund: 0,//最大可退款金额
            refundShow: 0,
            images: [],      //图片
            reason: '',      //原因
            imageMax: 5,    //用于前台判断上传图片按钮是否显示
            refundInputNoedit: true,
            mode: 'aspectFill',
            submitStatus: false,
            checkedItems: [],//当前选中的商品
            isFlag: true,
            costFreight: 0,//运费
            alertDescription: '如果订单未发货，只需要勾选需要退款的产品即可，如果已经发货，可以设置需要退货的产品数量。',
        }
    },
    computed: {
        isImage() {
            let num = this.imageMax - this.images.length;
            return num > 0;
        },
    },
    methods: {
        hanlderChangeReturnNums(e, index) {  
            this.items[index].returnNums = e.value;
            this.getReturnData();
        },
        // 单选框点击切换
        radioChange: function (evt) {
            this.typeList.forEach(item => {
                if (item.value === evt.target.value) {
                    item.checked = true;
                    this.aftersaleType = parseInt(evt.target.value);
                } else {
                    item.checked = false;
                }
            });
            if (this.typeList[0].checked) {
                this.refundInputNoedit = true;
            } else {
                this.refundInputNoedit = false;
            }
        },
        //订单商品信息
        getOrderInfo() {
            let data = {
                id: this.orderId
            }
            this.$u.api.orderDetail(data).then(res => {
                if (res.status) {
                    //如果不是未支付的，已取消的，已完成的状态，就都可以售后
                    if (res.data.globalStatus != 1 && res.data.globalStatus != 6 && res.data.globalStatus != 7) {
                        //判断是已付款未发货，如果是，就禁用退货
                        let typeList = this.typeList;
                        if (res.data.shipStatus != 2 && res.data.shipStatus != 3) {
                            typeList[1].disabled = true;
                        }

                        //设置已选中的商品
                        let nums = 0;
                        for (var i = 0; i < res.data.items.length; i++) {

                            res.data.items[i].id = res.data.items[i].id.toString();
                            //this.itemIds = this.itemIds.concat({ id: res.data.items[i].id, nums: returnNums });
                            res.data.items[i].returnNums = 0
                            res.data.items[i].checked = false;

                            if ((res.data.items[i].nums - res.data.items[i].reshipNums) > 0) {
                                res.data.items[i].disabled = false;
                            } else {
                                res.data.items[i].disabled = true;
                            }
 
                            res.data.items[i].min = 0;
                            if (res.data.shipStatus == 1) {  // 未发货 
                                res.data.items[i].max = res.data.items[i].nums;
                            } else if (res.data.shipStatus == 2) { // 部分发货 
                                //res.data.items[i].max = res.data.items[i].nums - res.data.items[i].sendNums - res.data.items[i].reshipNums;
                                res.data.items[i].max = res.data.items[i].sendNums - res.data.items[i].reshipNums;
                            } else { // 已发货  部分退货  已退货
                                res.data.items[i].max = res.data.items[i].sendNums - res.data.items[i].reshipNums;
                            }  
                        }
                        this.items = res.data.items;

                        console.log(this.items);

                        // this.refund = this.$common.formatMoney((res.data.orderAmount - res.data.refunded), 2, '');
                        this.maxRefund = this.$common.formatMoney((res.data.orderAmount - res.data.refunded), 2, '');
                        this.costFreight = res.data.costFreight;//运费
                        this.refundShow = res.data.payedAmount - res.data.refunded;
                        this.typeList = typeList;
                    } else {
                        this.$common.errorToBack('订单不可以进行售后');
                    }
                } else {
                    this.$common.errorToBack('没有找到此订单');
                }
            });
        },

        //退货商品选择
        checkboxChange(e) {
            //let nums = 0;
            //let id = 0;
            //this.itemIds = [];
            //for (var i = 0; i < e.detail.value.length; i++) {
            //    let k = e.detail.value[i];
            //    for (var j = 0; j < this.items.length; j++) {
            //        if (this.items[j].id == k) {
            //            if (this.items[j].nums > this.items[j].reshipNums) {
            //                // nums = this.items[j].sendnums - this.items[j].reshipNums;
            //                //nums = this.$refs.input[i].value
            //                nums = this.items[j].returnNums;
            //                id = parseInt(k);
            //                this.itemIds = this.itemIds.concat({ id: id, nums: nums });
            //                console.log(this.itemIds)
            //            }
            //        }
            //    }
            //}
            let id = e.target.dataset.itemid
            let idx = this.checkedItems.findIndex(item => item == id)
            if (idx >= 0) {
                this.checkedItems.splice(idx, 1)
            } else {
                this.checkedItems.push(id);
            }
            this.getReturnData();

        },

        // 点击输入框的事件
        onFocus(item, key) {
            item.returnNums = '';
            if (this.checkedItems.indexOf(item.id) == -1) {
                this.checkedItems.push(item.id)
            }
            this.items[key].checked = true;
            this.getReturnData();
            console.log(this.checkedItems);
        },
        //处理退款金额光标事件
        refundFocus(e) {
            this.refund = '';
        },

        //数量改变事件
        updateNum(updateNum, key) {
            let nums = 0;
            nums = this.items[key].nums - this.items[key].reshipNums;
            if (nums < updateNum.returnNums) {
                this.isFlag = false;
                this.items[key].returnNums = nums;
                this.$u.toast("您填写的数量不对！")
                //return false;
            }
            if (updateNum.returnNums == '') {
                this.items[key].returnNums = nums;
            }
            this.isFlag = true;
            this.items[key].returnNums = updateNum.returnNums;
            this.getReturnData();
        },

        //计算要退货的商品数量
        getReturnData() {
            //let nums = 0;
            ////this.itemIds = [];
            //for (var i = 0; i < this.checkedItems.length; i++) {
            //    let k = this.checkedItems[i];
            //    for (var j = 0; j < this.items.length; j++) {
            //        if (this.items[j].id == k) {
            //            if (this.items[j].nums >= this.items[j].reshipNums) {
            //                nums = this.items[j].nums - this.items[j].reshipNums;
            //                if (nums >= this.items[j].returnNums) {
            //                    nums = this.items[j].returnNums
            //                    //this.itemIds = this.itemIds.concat({ id: k, nums: nums });
            //                    this.itemIds.forEach((item, index, arr) => {
            //                        if (item.id == k) {
            //                            item.nums = nums;
            //                        }
            //                        //    console.log(index + ":" + item)
            //                    })
            //                } else {
            //                    this.$u.toast("您填写的数量不对！")
            //                    return;
            //                }
            //            }
            //        }
            //    }
            //}

 
            this.itemIds = [];
            let total_refund = 0;//最退款金额 
            let checkNums = 0;

            this.checkedItems.forEach((item) => {
                let data = this.items.find((itemChid) => itemChid.id == item);
                if (Object.keys(data).length) {

                    let returnNums = 0;
                    if (data.sendNums > 0) {  // 如果是仅退款，退款数量应为购买数量
                        returnNums = data.returnNums;
                    } else {   
                        returnNums = data.nums;
                    }

                    checkNums += returnNums;
                    this.itemIds.push({
                        id: data.id,
                        nums: returnNums,
                        sendNums:data.sendNums,
                    }); 

                    if (returnNums == (data.nums - data.reshipNums)) {
                        total_refund += (data.amount * 100 - data.reshipNums * data.price * 100) / 100;
                    } else {
                        total_refund += (data.price * returnNums * 100) / 100;
                    } 
                }
            })

            // for (var i = 0; i < this.checkedItems.length; i++) {
            //     let k = this.checkedItems[i];
            //     for (var j = 0; j < this.items.length; j++) {
            //         if (this.items[j].id == k) {
            //             if (this.items[j].nums >= this.items[j].reshipNums) {

            //                 nums = this.items[j].nums - this.items[j].reshipNums;
            //                 if (nums >= this.items[j].returnNums) {
            //                     nums = this.items[j].returnNums

            //                     checkNums += nums

            //                     this.item_ids = this.item_ids.concat({ id: k, nums: nums });
            //                     console.log('nums', nums, this.items[j], nums, (this.items[j].nums - this.items[j].reshipNums));
            //                     if (nums == (this.items[j].nums - this.items[j].reshipNums)) {
            //                         total_refund += (this.items[j].amount * 100 - this.items[j].reshipNums * this.items[j].price * 100) / 100;
            //                     } else {
            //                         total_refund += (this.items[j].price * nums * 100) / 100;
            //                     }
            //                 } else {
            //                     this.$common.errorToShow("您填写的数量不对！")
            //                     return;
            //                 }
            //             }
            //         }
            //     }
            // }

            if (checkNums + this.reshipNumsAll == this.buyNums) {

                if (this.reSult.costfreightstatus == 1) {
                    this.refund = total_refund.toFixed(2);
                } else {
                    this.refund = (Number(total_refund) + Number(this.costfreight)).toFixed(2);
                }
            } else {
                this.refund = total_refund.toFixed(2);
            }


        },

        //提交
        submit(e) {
            let _that = this;
            this.submitStatus = true;

            //判断退款金额
            if (!this.$u.test.amount(this.refund)) {
                this.$u.toast('请输入正确金额');
                this.submitStatus = false;
                return false;
            } else {
                if (this.refund > this.refundShow) {
                    this.$u.toast('退款金额过大');
                    this.submitStatus = false;
                    return false;
                }
            }
            if (!this.isFlag) {
                this.$u.toast('您填写的数量不对！');
                this.submitStatus = false;
                return false;
            }
            console.log(this.itemIds)
            if (this.itemIds.length <= 0) {
                this.$u.toast('请选择要售后的商品');
                this.submitStatus = false;
                return false;
            }
            _that.itemIds.forEach((item) => {
                if (item.sendNums == 0) {
                    item.nums = 0
                }
            })
            //组装数据，提交数据
            let data = {
                orderId: _that.orderId,
                type: _that.aftersaleType,
                items: _that.itemIds,
                images: _that.images,
                refund: _that.refund,
                reason: _that.reason
            };
            _that.$u.api.addAfterSales(data).then(res => {
                _that.submitStatus = false;
                if (res.status) {
                    _that.$refs.uToast.show({
                        message: '提交成功', type: 'success', complete: function () {
                            _that.$u.route("/pages/member/order/detail/detail?orderId=" + _that.orderId)
                        }
                    })
                } else {
                    _that.$u.toast(res.msg);
                }
            });
        },

        //上传图片
        upImage() {
            let num = this.imageMax - this.images.length;
            if (num > 0) {
                this.$upload.uploadImage(num, res => {
                    if (res.status) {
                        this.images.push(res.data.src);
                        this.$refs.uToast.show({ message: res.msg, type: 'success', back: false });
                    } else {
                        this.$u.toast(res.msg);
                    }
                });
            }
        },
        //删除图片
        delImage(e) {
            let newImages = [];
            for (var i = 0; i < this.images.length; i++) {
                if (this.images[i].image_id != e.image_id) {
                    newImages.push(this.images[i]);
                }
            }
            this.images = newImages;
        },
        // 图片点击放大
        clickImg(img) {
            // 预览图片
            uni.previewImage({
                urls: img.split()
            });
        }
    },
    onLoad(e) {
        this.orderId = e.orderId;
        this.getOrderInfo();
        this.getReturnData()
    }
}
</script>

<style lang="scss" scoped>
@import "submit.scss";
</style>
